package chances.system.operator.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import chances.system.log.entity.ActionLog;
import chances.system.operator.entity.Oplog;

@Controller
public class LogonController{

	@ActionLog(operateType=Oplog.OP_LOGIN, objName="user", desc="用户'{name}'登陆")
	@RequestMapping(value = "/logon", method = RequestMethod.GET)
	public String logon(HttpServletRequest request, HttpServletResponse response) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		
		if(authentication != null){
			request.setAttribute("user", ((OperatorSession)authentication.getPrincipal()).getOperator());
		}
		
		//将用户的登陆信息存放到session中
		HttpSession session = request.getSession();
		session.setAttribute("user", ((OperatorSession)authentication.getPrincipal()).getOperator());
		return "common/login/logon";
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest httpServletRequest, Model model) {
		return "common/login/login";
	}
	
	@ActionLog(operateType=Oplog.OP_LOGOUT, objName="user", desc="用户'{name}'退出", operator="operator")
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response, Model model) {
		OperatorSession.removeOperatorSession(request);
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if(authentication != null){
			Object principal = authentication.getPrincipal();
			if(principal != null){
				OperatorSession operatorSession = 
						(OperatorSession)request.getAttribute(OperatorSession.SESSION_NAME);
				request.setAttribute("operator", operatorSession.getOperator());
				request.setAttribute("user", operatorSession.getOperator());
			}
		}

		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth != null){    
			new SecurityContextLogoutHandler().logout(request, response, auth);
		}
		return "common/login/logout";
	}

}
